package com.geeklan.smart.data.remote;

import com.geeklan.smart.data.auth.AuthManager;
import com.geeklan.smart.utils.SharedPreferencesUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        // 在请求头中添加 Authorization Token
        Request modifiedRequest = originalRequest.newBuilder()
                .header("Authorization", SharedPreferencesUtil.getString("token",""))
                .build();

        Response response = chain.proceed(modifiedRequest);
        ResponseBody responseBody = response.body();
        String responseBodyString = response.body() != null ? response.body().string() : "";

        JsonObject jsonResponse = JsonParser.parseString(responseBodyString).getAsJsonObject();

        int code = jsonResponse.has("code") ? jsonResponse.get("code").getAsInt() : -1;

        if(code == 401){
            AuthManager.getInstance().logoutAndRedirectToLogin();
        }

        // 为了继续后续的使用，我们需要重新创建 ResponseBody（因为原始的 ResponseBody 已经被消耗）
        ResponseBody newResponseBody = ResponseBody.create(responseBody.contentType(), responseBodyString);


        return response.newBuilder()
                .body(newResponseBody)  // 使用新的 ResponseBody
                .build();
    }
}

